package com.broada.apm.es.handler;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.wink.client.ClientResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.broada.apm.es.bean.Snapshot;
import com.broada.apm.utils.EsClientUtil;
import com.broada.apm.utils.JsonUtil;
import com.broada.apm.utils.RestClientUtil;

/**
 * 
 * 数据备份恢复操作类 快照保存的是在开始进行创建快照的那个时间点的索引的视图。 所以，在开始创建快照之后的记 录不会出现在这个快照里
 * 
 * @author louyi Create By Dec 3, 2014 10:11:37 AM
 */

public class ApmDataBackUpHandler {
	private Logger log = LoggerFactory.getLogger(ApmDataBackUpHandler.class);

	private String storage = "apm_backup_%s_%s_%s";
	// 生产性能快照url
	private String CREATE_SNAPSHORT = "/_snapshot/apm/%s";
	// Optimize index 优化索引用于快速搜索操作 url
	private String OPTIMIZE_INDEX = "/_optimize";
	// Flush index 释放内存数据的索引存储和清理内部事务日志 url
	private String FLUSH_INDEX = "/_flush";
	// 监控进度url
	private String PROCESS_STATUS = "/_snapshot/apm/%s";

	public void dobackup(String fileName) {
		String url = EsClientUtil.getEsHttpUrl();
		if (StringUtils.isEmpty(fileName)) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new Date());
			int year = calendar.get(Calendar.YEAR);
			int month = calendar.get(Calendar.MONTH) + 1;
			int day = calendar.get(Calendar.DAY_OF_MONTH);
			fileName = String.format(storage, year, month, day);
		}
		// 优化索引用于快速搜索操作
		RestClientUtil.doAction("post", url + OPTIMIZE_INDEX, "");
		log.info("优化索引...");
		// Flush index 释放内存数据的索引存储和清理内部事务日志
		RestClientUtil.doAction("post", url + FLUSH_INDEX, "");
		log.info("Fulsh 索引");
		// 开始备份生产性能快照
		RestClientUtil.doAction("put", String.format(url + CREATE_SNAPSHORT, fileName), "");
		log.info("开始备份生产性能数据 dest:" + String.format(url + CREATE_SNAPSHORT, fileName));
	}

	@SuppressWarnings("rawtypes")
	public Snapshot getProgress(String fileName) throws Exception {
		String url = EsClientUtil.getEsHttpUrl();
		ClientResponse response = RestClientUtil.doAction("get", String.format(url + PROCESS_STATUS, fileName), "");
		Map map = JsonUtil.json2map(response.getEntity(String.class));
		List snapshots = (List) map.get("snapshots");
		return JsonUtil.map2obj((Map) snapshots.get(0), Snapshot.class);
	}
}